//
//  RBDataFilterView.m
//  WaitBuyer
//
//  Created by Lan on 2018/11/10.
//  Copyright © 2018年 SummerTea. All rights reserved.
//

#import "RBDataFilterView.h"
#import "RBDefine.h"
#import "UIButton+RBAdd.h"
#import <Masonry.h>
#import "RBThemeConfig.h"
#import <UIView+YYAdd.h>
#import "RBAppDelegateHelper.h"
#import "UIView+RBAdd.h"
#import "UIColor+YYAdd.h"

@interface RBDataFilterListCell:UITableViewCell

@property(nonatomic, strong) UILabel *textL;

@end

@implementation RBDataFilterListCell

- (UILabel *)textL
{
    if (!_textL)
    {
        self.textL = ({
            UILabel *view = [UILabel new];
            view.textColor = [RBThemeConfig textBlackColor];
            view.font = [UIFont systemFontOfSize:13];
            view.numberOfLines = 1;
            view.textAlignment = NSTextAlignmentLeft;
            [self.contentView addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.mas_equalTo(0);
                make.left.mas_equalTo(15);
                make.right.mas_equalTo(-15);
            }];
            view;
        });
    }
    return _textL;
}

@end

@interface RBDataFilterListView:UIView

- (void)showWithData: (NSArray *)data
              height: (CGFloat)height
                 top: (CGFloat)top;

@property(nonatomic, copy) void(^cancelBlock)(void);
@property(nonatomic, copy) void(^confirmBlock)(NSString *text, NSInteger index);

@end

@interface RBDataFilterListView()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong) UIView *bgView;
@property(nonatomic, strong) UITableView *tableview;
@property(nonatomic, assign) CGFloat hTop;
@property(nonatomic, assign) CGFloat hHeight;
@property(nonatomic, strong) NSArray *dataSource;

@end

@implementation RBDataFilterListView

#pragma mark - Public

- (void)showWithData:(NSArray *)data height:(CGFloat)height top:(CGFloat)top
{
    self.frame = kRBMainScreenBounds;
    [[RBAppDelegateHelper keyWindow] addSubview:self];
    
    self.hTop = top;
    self.hHeight = height;
    
    [self.bgView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(top);
    }];
    
    [self.tableview mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(top);
        make.height.mas_equalTo(MIN(kRBMainScreenHeight - top - 100, data.count*40));
    }];
    self.dataSource = data;
    [self.tableview reloadData];
}

#pragma mark - Event

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.cancelBlock)
    {
        self.cancelBlock();
    }
    [self removeFromSuperview];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (point.y >= self.hTop - self.hHeight && point.y <= self.hTop)
    {
        return nil;
    }
    else if (CGRectContainsPoint(self.tableview.frame, point))
    {
        return self.tableview;
    }
    else
    {
        return self;
    }
}

- (void)bgViewTapped
{
    if (self.cancelBlock)
    {
        self.cancelBlock();
    }
    [self removeFromSuperview];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RBDataFilterListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell)
    {
        cell = [[RBDataFilterListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.textL.text = self.dataSource[indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.confirmBlock)
    {
        self.confirmBlock(self.dataSource[indexPath.row], indexPath.row);
    }
    [self removeFromSuperview];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

#pragma mark - Getter

- (UIView *)bgView
{
    if (!_bgView)
    {
        self.bgView = ({
            UIView *view = [UIView new];
            [view rbAddTapGesWithTarget:self action:@selector(bgViewTapped)];
            view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            view;
        });
    }
    return _bgView;
}

- (UITableView *)tableview
{
    if (!_tableview) {
        self.tableview = ({
            UITableView *tableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
            tableview.dataSource = self;
            tableview.delegate = self;
            tableview.showsVerticalScrollIndicator = NO;
            tableview.showsHorizontalScrollIndicator = NO;
            tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
            tableview.tableFooterView = [UIView new];
            [self addSubview:tableview];
            [tableview mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            tableview;
        });
    }
    return _tableview;
}

@end

@interface RBDataFilterView()

@property(nonatomic, strong) UIView *line;
@property(nonatomic, strong) UIStackView *stackView;
@property(nonatomic, strong) NSArray *filters;

@property(nonatomic, copy) void(^block)(NSInteger, NSInteger, NSString *);

@end

@implementation RBDataFilterView

- (void)dealloc
{
    
}

#pragma mark - Public

+ (instancetype)viewWithFilters:(NSArray *)filters selectBlock:(void (^)(NSInteger, NSInteger, NSString *))block
{
    RBDataFilterView *view = [RBDataFilterView new];
    view.autoScroll = YES;
    view.width = kRBMainScreenWidth;
    view.height = 47;
    view.filters = filters;
    for (NSInteger i = 0; i < filters.count; i++)
    {
        NSArray *items = filters[i];
        [view.stackView addArrangedSubview:[view subViewWithTitle:items[0] tag:i]];
    }
    view.line.hidden = NO;
    [view addGestureRecognizer:({
        UIPanGestureRecognizer *ges = [[UIPanGestureRecognizer alloc] initWithTarget:view action:@selector(pan)];
        ges;
    })];
    view.block = block;
    return view;
}

#pragma mark - Private

- (UIScrollView *)superScrollView
{
    UIView *currentView = self;
    while (currentView.superview)
    {
        currentView = currentView.superview;
        if ([currentView isKindOfClass:[UIScrollView class]])
        {
            return (UIScrollView *)currentView;
        }
    }
    return nil;
}

- (void)resetArrows
{
    for (UIView *view in self.stackView.arrangedSubviews)
    {
        for (UIButton *btn in view.subviews)
        {
            if ([btn isKindOfClass:[UIButton class]])
            {
                btn.selected = NO;
                [btn rbSetImage:[UIImage imageNamed:@"down_arrow"]];
            }
        }
    }
}

- (void)setTitle: (NSString *)title withBtnIndex: (NSInteger)index
{
    for (UIView *view in self.stackView.arrangedSubviews)
    {
        for (UIButton *btn in view.subviews)
        {
            if ([btn isKindOfClass:[UIButton class]] && index == btn.tag)
            {
                [btn rbSetTitle:[title stringByAppendingString:@" "]];
            }
        }
    }
}

- (BOOL)scrollAnimated: (BOOL)animated
{
    if ([self superScrollView])
    {
        UIScrollView *scrollView = [self superScrollView];
        CGRect frame = [self.superview convertRect:self.frame toView:scrollView];
        if (frame.origin.y > 0)
        {
            CGFloat offsetY = frame.origin.y;
            offsetY = MIN(offsetY, scrollView.contentSize.height - scrollView.frame.size.height);
            if (offsetY > 0 && scrollView.contentOffset.y != offsetY)
            {
                [UIView animateWithDuration:animated? 0.3: 0 animations:^{
                    scrollView.contentOffset = CGPointMake(0, offsetY);
                }];
                return YES;
            }
        }
    }
    return NO;
}

#pragma mark - Event

- (void)btnTapped: (UIButton *)btn
{
    //列表视图
    RBDataFilterListView *listView;
    for (RBDataFilterListView *subView in [RBAppDelegateHelper keyWindow].subviews)
    {
        if ([subView isKindOfClass:[RBDataFilterListView class]])
        {
            listView = subView;
        }
    }
    
    //再次选取,dismiss掉
    if (btn.selected)
    {
        [listView touchesBegan:[NSSet set] withEvent:nil];
        return;
    }
    
    //位移
    if ([self superScrollView] && self.autoScroll)
    {
        UIScrollView *scrollView = [self superScrollView];
        CGRect frame = [self.superview convertRect:self.frame toView:scrollView];
        if (frame.origin.y > 0)
        {
            CGFloat offsetY = frame.origin.y;
            offsetY = MIN(offsetY, scrollView.contentSize.height - scrollView.frame.size.height);
            if (offsetY > 0)
            {
                scrollView.contentOffset = CGPointMake(0, offsetY);
            }
        }
    }
    //旋转
    [self resetArrows];
    [btn rbSetImage:[UIImage imageNamed:@"up_arrow"]];
    btn.selected = YES;
    
    //展示列表
    __weak typeof(self) weak_self = self;
    if (!listView)
    {
        listView = [RBDataFilterListView new];
    }
    listView.cancelBlock = ^{
        [weak_self superScrollView].scrollsToTop = YES;
        [weak_self resetArrows];
    };
    NSInteger section = btn.tag;
    listView.confirmBlock = ^(NSString *text, NSInteger index) {
        [weak_self superScrollView].scrollsToTop = YES;
        [weak_self resetArrows];
        if (index == 0)
        {
            text = [weak_self.filters[section] firstObject];
            
        }
        if (weak_self.block)
        {
            weak_self.block(section, index, text);
        }
        [weak_self setTitle:text withBtnIndex:section];
        
    };
    [self superScrollView].scrollsToTop = NO;
    [listView showWithData:({
        NSMutableArray *arrayM = [NSMutableArray arrayWithArray:self.filters[btn.tag]];
        [arrayM removeObjectAtIndex:0];
        arrayM;
    }) height:self.height top:CGRectGetMaxY([self.superview convertRect:self.frame toView:[RBAppDelegateHelper keyWindow]]) + .5];
}

- (void)pan
{
    //屏蔽控制器返回手势
}

#pragma mark - Getter

- (UIView *)subViewWithTitle: (NSString *)title tag: (NSInteger)tag
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    
    UIButton *btn = [UIButton new];
    btn.tag = tag;
    [btn rbSetTitleColor:[RBThemeConfig textBlackColor]];
    [btn rbSetFontSize:13];
    [btn rbAddTarget:self action:@selector(btnTapped:)];
    [btn rbSetTitle:[title stringByAppendingString:@" "]];
    [btn rbSetImage:[UIImage imageNamed:@"down_arrow"]];
    btn.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;
    [view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(0);
        make.left.mas_equalTo(5);
        make.right.mas_equalTo(-5);
    }];
    
    return view;
}

- (UIStackView *)stackView
{
    if (!_stackView)
    {
        self.stackView = ({
            UIStackView *view = [UIStackView new];
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            view.axis = UILayoutConstraintAxisHorizontal;
            view.distribution = UIStackViewDistributionFillEqually;
            view;
        });
    }
    return _stackView;
}

- (UIView *)line
{
    if (!_line)
    {
        self.line = ({
            UIView *view = [UIView new];
            view.backgroundColor = [UIColor colorWithHexString:@"bcbbc1"];
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.mas_equalTo(0);
                make.height.mas_equalTo(0.5);
            }];
            view;
        });
    }
    return _line;
}

@end
